package com.boot.crm.springBoot.springDataJPA;

import com.boot.crm.springBoot.springDataJPA.model.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by ys on 2018/8/26.
 */
@RestController
public class DataController {
    //1.Spring Data JPA 已自动为你注册bean，所以可自动注入 (继承了JPA的类)
    @Autowired
    private PersonRepository personRepository;

    /**
     * 保存
     * */
    @RequestMapping("/save")//http://localhost:9090/crm_boot/save?name=dd&address=上海&age=26
    public Person save(String name,String address,Integer age){
        Person person = personRepository.save(new Person(null, name, age, address));
        return person;
    }
    /**
     * 测试findByAddress
     */
    @RequestMapping("/q1")//http://localhost:9090/crm_boot/q1?address=上海
    public List<Person> q1(String address){
        List<Person> byAddress = personRepository.findByAddress(address);
        return byAddress;
    }
    /**
     * 测试findByNameAndAddress
     */
    @RequestMapping("/q2")
    public Person q2(String name,String address){
        Person person = personRepository.findByNameAndAddress(name, address);
        return person;
    }
    /**
     * 测试 withNameAndAddressQuery
     */
    @RequestMapping("/q3")//http://localhost:9090/crm_boot/q3?address=上海&name=dd1
    public Person q3(String name,String address){
        Person person = personRepository.withNameAndAddressQuery(name, address);
        return person;
    }
    /**
     * 测试 withNameAndAddressNamedQuery
     */
    @RequestMapping("/q4")//http://localhost:9090/crm_boot/q4?address=%E4%B8%8A%E6%B5%B7&name=dd1
    public Person q4(String name , String address){
        Person person = personRepository.withNameAndAddressNamedQuery(name, address);
        return person;
    }
    /**
     * 测试排序
     */
    @RequestMapping("/sort")//http://localhost:9090/crm_boot/sort
    public  List<Person> sort(){
        List<Person> people = personRepository.findAll(new Sort(Sort.Direction.ASC, "age"));
        return people;
    }
    /**
     * 测试分页
     */
    @RequestMapping("/page")
    public Page<Person> page(){
        Page<Person> people = personRepository.findAll(new PageRequest(1, 2));
        return people;
    }
}
